package actions;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DBModel;

@WebServlet
public class DeleteEventAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response){
		try{
			int eventId = Integer.parseInt(request.getParameter("id"));
			if(!hasRights(request,eventId)){
				System.out.println("Not a moderator or admin");
				//response.sendRedirect("Event?id="+eventId);
				return mapping.findForward("fail");
			}
			else{
				DBModel db=new DBModel();
				db.deleteEvent(eventId);
				db.commit();
				db.close();
				if(request.isUserInRole("admin")){
					return mapping.findForward("adminSuccess");
				}
				else{
					return mapping.findForward("success");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("error", e.toString());
			return mapping.findForward("fail");
		}
			
	}
	
	private boolean hasRights(HttpServletRequest request, int eventId){
		try{
			boolean isAdmin = request.isUserInRole("admin");
			if(!isAdmin){
				String activeUser = request.getUserPrincipal().getName();
				DBModel db = new DBModel();
				return db.isModeratorOfEvent(activeUser, eventId);
			}
			else return true;
		}catch(Exception e){
			return false;
		}
	}

}
